/*
 * Name: Joon Ho Cho
 * Date: 10/24/2008
 * Course: 15-437
 */
package scheduler.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.mybeans.dao.DAOException;
import org.mybeans.forms.FormBeanFactory;

import scheduler.databean.User;
import scheduler.formbean.ChangeCommentForm;
import scheduler.formbean.LoginForm;
import scheduler.model.BookmarkDao;
import scheduler.model.Model;
import scheduler.model.UserDao;


public class ModifyEntryAction extends Action {
	private static FormBeanFactory<ChangeCommentForm> formBeanFactory =
						FormBeanFactory.getInstance(ChangeCommentForm.class,"<>\"");
	private BookmarkDao bookmarkDao;
	private UserDao userDao;
	
    public ModifyEntryAction(Model model) {
    	bookmarkDao = model.getBookmarkDao();
    	userDao = model.getUserDao();
	}

    public String getName() { return "modify-entry.do"; }

    public String perform(HttpServletRequest request) {
        	ChangeCommentForm form = formBeanFactory.create(request);
	    	List<String> errors = form.getValidationErrors();
			request.setAttribute("form",form);
	        request.setAttribute("errors",errors);
	    	if (errors.size() > 0) return "modify.jsp";

			// Must be logged in for this one
	    	HttpSession session = request.getSession();
	        User user = (User) session.getAttribute("user");
			if (user == null) {
				LoginForm loginForm = new LoginForm();
				loginForm.setRedirect("/modify-entry.do");
		        request.setAttribute("form",loginForm);
				return "login.jsp";
			}
			
	        try {
				bookmarkDao.update(form.getId(), form.getNewComment());
				
				request.setAttribute("bookmarks", null);
				request.setAttribute("bookmarks", bookmarkDao.getBookmarksForUser(user.getUserName()));

				request.setAttribute("registeredUsers", userDao.getAll());
			} catch (DAOException e) {
	        	e.printStackTrace();
	        	request.setAttribute("dbError",e.getMessage());
	        	return "db-error.jsp";
			}

	    	return "manage.jsp";
    }
}
